from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


# 序列化OpenID
def generate_save_user_token(openid):
    # 创建序列器，serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, 300)
    # serializer.dumps(数据), 返回bytes类型
    token = serializer.dumps({'openid': openid})
    # 返回token
    return token.decode()


def check_save_user_token(access_token):
    """校验access_token"""
    # 创建序列器，serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, 300)
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')